package com.lw.forkjoin;

/**
 * @author LW
 * @2020/8/21 10:37
 */

import java.io.Serializable;
import java.util.concurrent.RecursiveTask;

/**Recursive   递归
 *
 * Stream并行流 > ForkJoin  >   普通计算
 * 如何使用Forkjoin
 * ForkJoinPool
 */
public class ForkJoinDemo extends RecursiveTask<Long> implements Serializable {
    private static final long serialVersionUID = 2462375556031755900L;

    /**
     * Long是对象    long是基本类型
     */
    private long start;
    private long end;

    //临界值
    private static final long temp =10000L;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }
    @Override
    //计算方法
    protected Long compute() {
        //大于临界值     进行       分之合并计算
        if ((end-start)>temp){
            //分之合并计算
            long sum = 0;
            //JDK1.7的  分割符
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            //fork/join
            long m = (start+end)/2;
            ForkJoinDemo task1 = new ForkJoinDemo(start,m);
            task1.fork();//拆分任务，把任务压入队列
            ForkJoinDemo task2 = new ForkJoinDemo(m+1,end);
            task2.fork();
            //合并
            return task1.join()+task2.join();
        }

    }

}
